﻿namespace MSBuild.MKS.Tasks
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    using Microsoft.Build.Framework;
    using Microsoft.Build.Utilities;

    /// <summary>
    /// The determine new files.
    /// </summary>
    public class DetermineNewFiles : Task
    {
        #region Constants and Fields

        #endregion

        #region Public Properties

        /// <summary>
        /// Gets or sets Files.
        /// </summary>
        [Required]
        public ITaskItem[] Files { get; set; }

        /// <summary>
        /// Gets or sets NewFiles.
        /// </summary>
        [Output]
        public ITaskItem[] NewFiles { get; set; }

        /// <summary>
        /// Gets or sets OriginalFiles.
        /// </summary>
        [Required]
        public ITaskItem[] OriginalFiles { get; set; }

        #endregion

        #region Public Methods

        /// <summary>
        /// Executes the task.
        /// </summary>
        /// <returns>
        /// The execute result.
        /// </returns>
        public override bool Execute()
        {
            try
            {
                this.FindNewFiles();
                return true;
            }
            catch (Exception ex)
            {
                this.Log.LogError("Exception during {0} procedure: {1}", this.GetType().Name, ex.GetType().Name);
                this.Log.LogError("Exception details: {0}", ex.Message);
                return false;
            }
        }

        #endregion

        #region Methods

        /// <summary>
        /// The find new files.
        /// </summary>
        private void FindNewFiles()
        {
            var items = from x in this.Files where !this.IsInOriginalSet(x.ItemSpec) select x;

            if (items.Count() > 0)
            {
                this.NewFiles = items.ToArray();
            }
            else
            {
                var blank = new List<ITaskItem>();
                this.NewFiles = blank.ToArray();
            }
        }

        /// <summary>
        /// Determines if an item is in the original set of items.
        /// </summary>
        /// <param name="itemSpec">
        /// The item spec.
        /// </param>
        /// <returns>
        /// The is in original set.
        /// </returns>
        private bool IsInOriginalSet(string itemSpec)
        {
            var items = from x in this.OriginalFiles where x.ItemSpec == itemSpec select x;

            return items.Count() > 0;
        }

        #endregion
    }
}